package com.xywy.common.net;

import java.io.File;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.SocketException;
import java.net.URLEncoder;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.http.Consts;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.cookie.Cookie;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.AbstractHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;

import com.xywy.R;
import com.xywy.common.app.DeviceInfo;
import com.xywy.common.app.MainApplication;
import com.xywy.common.constants.ErrorCode;
import com.xywy.common.util.MD5Util;
import com.xywy.common.util.MLog;
import com.xywy.common.util.StringUtils;

/**
 * 名称: NetUtil
 * 描述: 网络工具类
 *
 * @author  xgd
 */
public class NetUtil {
    private static final String TAG = "NetUtil";
    private static HttpClient client;
    private ArrayList<String> filter;
    //session
    

    private static HashMap<Object, Object> save_map = new HashMap<Object, Object>() {
        @Override
        public int hashCode() {
            List<Integer> results = new ArrayList<Integer>();
            int result = 0;
            Iterator<Object> it = keySet().iterator();
            while (it.hasNext()) {
                result += it.next().hashCode();
                if (results.contains(result)) {
                    MLog.e(TAG, "哈西值重复");
                } else {
                    results.add(result);
                }
            }
            return result;
        }

        @Override
        public Object remove(Object key) {
            return super.remove(key);
        }

        @Override
        public Object put(Object key, Object value) {
            return super.put(key, value);
        }
    };


    private NetUtil() {
        filter = new ArrayList<String>();
    }

    /**
     * 静态单例
     */
    public static NetUtil getInstance() {
        return singletonHolder.instance;
    }

    private static class singletonHolder {
        private static NetUtil instance = new NetUtil();
    }

    /**
     * get的一个重载 (T accessTokenPaser)
     *
     * @param parser
     * @return
     */
    public static <T extends Parser> T get(T parser) {
        HashMap<String, Object> map = parser.map;
        Context context = parser.context;
        String action = parser.action;

        //公共sign
        try {
            String  tag = context.getString(R.string.common_tag);
            map.put("tag",tag);
            map.put("sign", MD5Util.md5(context.getString(R.string.common_sign)+tag));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        client = ((MainApplication) context.getApplicationContext()).getHttpClient();
        String str = "";
        Set<String> key = map.keySet();
        StringBuffer sb = new StringBuffer();
        for (Iterator<String> it = key.iterator(); it.hasNext(); ) {
            String s = it.next();
            if (s == null || map.get(s) == null)
                continue;
            try {
                sb.append(s + ":");
                sb.append(map.get(s) + "\t");
                str += s + "="
                        + URLEncoder.encode(map.get(s).toString(), "utf-8")
                        + "&";
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (str.length() > 0) {
            str = str.substring(0, str.length() - 1);
        }
        MLog.i(TAG, "GET:参数====" + sb.toString());
        try {
            String url = context.getString(R.string.app_host) + action;
            String uriget = url + str;
            MLog.i(TAG, "GET:请求的连接=====: " + uriget);
            Log.e(TAG, "GET:请求的连接=====: " + uriget);
            HttpGet get = new HttpGet(uriget);

            save_map.put(parser, get); // 将正在处理的对象加入集合
            HttpResponse response = client.execute(get);
            MLog.i(TAG,"response.getStatusLine().getStatusCode(); 记录下状态码:"+response.getStatusLine().getStatusCode());
            try {
                parser.statusCode = response.getStatusLine().getStatusCode(); // 记录下状态码
                if (parser.statusCode == HttpStatus.SC_OK) {
                    parser.back = EntityUtils.toString(response.getEntity(), "UTF-8");
                    MLog.i(TAG, "返回的数据===" + parser.back);
                }
            } catch (ClientProtocolException e) {
                parser.statusCode = ErrorCode.ERR_CLIENTPROTOCOL;
                MLog.e(TAG, "不符合协议格式", e);
            }
        } catch (ConnectTimeoutException e) {
            parser.statusCode = ErrorCode.ERR_TIMEOUT;
            MLog.e(TAG, "网络连接超时", e);
        } catch (IllegalStateException e) {
            parser.statusCode = ErrorCode.POOL_SHUT_DOWN;
            MLog.e(TAG, "连接池关闭了", e);
        } catch (SocketException e) {
            MLog.i(TAG, e.getMessage());
            if (e.getMessage().contains("ECONNRESET")) {
                parser.statusCode = ErrorCode.ERR_SOCKET;
                MLog.e(TAG, "错误的链接", e);
            } else {
                parser.statusCode = ErrorCode.SHUTDOWN;
                MLog.e(TAG, "端口中断，被中断了", e);
            }
        } catch (Exception e) {
            parser.statusCode = ErrorCode.ERR_UNKNOWN;
            MLog.e(TAG, "网络错误", e);
        } finally {
            save_map.remove(parser);
        }
        return parser;
    }


    /**
     * post请求
     *
     * @param parser
     * @return
     */
    public static <T extends Parser> T post(T parser) {
        HashMap<String, Object> map = parser.map;

        Context context = parser.context;
        //公共sign
        try {
            String  tag = context.getString(R.string.common_tag);
            map.put("tag",tag);
            map.put("sign", MD5Util.md5(context.getString(R.string.common_sign)+tag));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        String action = parser.action;
        client = ((MainApplication) context.getApplicationContext()).getHttpClient();
        List<BasicNameValuePair> nameValuePair = new ArrayList<BasicNameValuePair>();
        String url = context.getString(R.string.app_host) + action;
        try {

            //封装参数
            packageParam(map, nameValuePair, parser.ifFilter);
            MLog.i(TAG, "--POST:提交到 服务器的url==" + url);
            MLog.i(TAG, "--POST:提交到 服务器的json数据==" + nameValuePair.toString());
            HttpPost post = new HttpPost(url);

            save_map.put(parser, post); // 将正在处理的对象加入集合
            // 对请求参数进行编码
            HttpEntity entity = new UrlEncodedFormEntity(nameValuePair,"utf-8");
            System.out.println("轉移后  "+entity.toString());
            post.setEntity(entity);

            MLog.i(TAG, "POST编码后的参数是::" + StringUtils.inputStreamToString(post.getEntity().getContent()));
            HttpResponse response = client.execute(post); // 执行POST方法 
            parser.statusCode = response.getStatusLine().getStatusCode(); // 返回码的获取，判断处理
            if (parser.statusCode == HttpStatus.SC_OK) {
                parser.back = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
            MLog.i(TAG, "返回的数据===" + StringUtils.unicodeToUtf8(parser.back));
        } catch (ClientProtocolException e) {
            parser.statusCode = ErrorCode.ERR_CLIENTPROTOCOL;
            MLog.e(TAG, "不符合协议格式", e);
        } catch (ConnectTimeoutException e) {
            parser.statusCode = ErrorCode.ERR_TIMEOUT;
            MLog.e(TAG, "网络连接超时");
        } catch (IllegalStateException e) {
            parser.statusCode = ErrorCode.POOL_SHUT_DOWN;
            MLog.e(TAG, "连接池关闭了", e);
        } catch (SocketException e) {
            if (e.getMessage().contains("ECONNRESET")) {
                parser.statusCode = ErrorCode.ERR_SOCKET;
                MLog.e(TAG, "错误的链接", e);
            } else {
                parser.statusCode = ErrorCode.SHUTDOWN;
                MLog.e(TAG, "端口中断，被中断了", e);
            }
        } catch (Exception e) {
            parser.statusCode = ErrorCode.ERR_UNKNOWN;
            MLog.e(TAG, "网络错误", e);
        } finally {
            save_map.remove(parser);
        }
        return parser;
    }

    /**
     * post请求 nameValuePair 存入的json
     *
     * @param parser
     * @return
     */
    public static <T extends Parser> T post(
            List<NameValuePair> nameValuePair, String url, T parser) {
        Context context = parser.context;
        client = ((MainApplication) context.getApplicationContext())
                .getHttpClient();
        MLog.d(TAG, "--POST:提交到 服务器的 url---" + url);
        MLog.d(TAG, "--POST:提交到 服务器的json数据--" + nameValuePair.toString());
        HttpPost post = new HttpPost(url);

        save_map.put(parser, post); // 将正在处理的对象加入集合
        try {
            // 对请求参数进行编码
            post.setEntity(new UrlEncodedFormEntity(nameValuePair, "UTF-8"));
            HttpResponse response = client.execute(post); // 执行POST方法
            parser.statusCode = response.getStatusLine().getStatusCode(); // 返回码的获取，判断处理
            if (parser.statusCode == HttpStatus.SC_OK) {
                parser.back = EntityUtils
                        .toString(response.getEntity(), "UTF-8");
                MLog.i(TAG, "返回的数据===" + parser.back);
            }
        } catch (ClientProtocolException e) {
            parser.statusCode = ErrorCode.ERR_CLIENTPROTOCOL;
            MLog.e(TAG, "不符合协议格式", e);
        } catch (ConnectTimeoutException e) {
            parser.statusCode = ErrorCode.ERR_TIMEOUT;
            MLog.e(TAG, "网络连接超时");
        } catch (IllegalStateException e) {
            parser.statusCode = ErrorCode.POOL_SHUT_DOWN;
            MLog.e(TAG, "连接池关闭了", e);
        } catch (SocketException e) {
            if (e.getMessage().contains("ECONNRESET")) {
                parser.statusCode = ErrorCode.ERR_SOCKET;
                MLog.e(TAG, "错误的链接", e);
            } else {
                parser.statusCode = ErrorCode.SHUTDOWN;
                MLog.e(TAG, "端口中断，被中断了", e);
            }
        } catch (Exception e) {
            parser.statusCode = ErrorCode.ERR_UNKNOWN;
            MLog.e(TAG, "网络错误", e);
        } finally {
            save_map.remove(parser);
        }
        return parser;
    }

    /**
     * get 请求 json
     *
     * @param parser
     * @return
     */
    public static <T extends Parser> T get(JSONObject json, String url, T parser) {
        Context context = parser.context;
        client = ((MainApplication) context.getApplicationContext())
                .getHttpClient();
        MLog.d(TAG, "--get json 提交到 服务器的 url---" + url);
        MLog.d(TAG, "--get json提交到 服务器的json数据--" + json.toString());
        String jsonStr = json.toString();
        jsonStr = jsonStr.substring(1, jsonStr.length() - 1);
        HttpGet get = new HttpGet(url + jsonStr);
        save_map.put(parser, get); // 将正在处理的对象加入集合
        try {
            // 对请求参数进行编码
            HttpResponse response = client.execute(get); // 执行GET方法
            // 返回码的获取，判断处理
            parser.statusCode = response.getStatusLine().getStatusCode();
            if (parser.statusCode == HttpStatus.SC_OK) {
                parser.back = EntityUtils
                        .toString(response.getEntity(), "UTF-8");
                MLog.i(TAG, "返回的数据===" + parser.back);
            }
        } catch (ClientProtocolException e) {
            parser.statusCode = ErrorCode.ERR_CLIENTPROTOCOL;
            MLog.e(TAG, "不符合协议格式", e);
        } catch (ConnectTimeoutException e) {
            parser.statusCode = ErrorCode.ERR_TIMEOUT;
            MLog.e(TAG, "网络连接超时");
        } catch (IllegalStateException e) {
            parser.statusCode = ErrorCode.POOL_SHUT_DOWN;
            MLog.e(TAG, "连接池关闭了", e);
        } catch (SocketException e) {
            if (e.getMessage().contains("ECONNRESET")) {
                parser.statusCode = ErrorCode.ERR_SOCKET;
                MLog.e(TAG, "错误的链接", e);
            } else {
                parser.statusCode = ErrorCode.SHUTDOWN;
                MLog.e(TAG, "端口中断，被中断了", e);
            }
        } catch (Exception e) {
            parser.statusCode = ErrorCode.ERR_UNKNOWN;
            MLog.e(TAG, "网络错误", e);
        } finally {
            save_map.remove(parser);
        }
        return parser;
    }

    public static <T extends Parser> T post(T parser,
                                               UrlEncodedFormEntity entity) {
        // 此处的map可以不指定
        Context context = parser.context;
        String action = parser.action;

        client = ((MainApplication) context.getApplicationContext())
                .getHttpClient();
        try {

            String url = context.getString(R.string.app_host) + action;
            HttpPost post = new HttpPost(url);

            save_map.put(parser, post); // 将正在处理的对象加入集合
            MLog.d(TAG, "--POST:提交到 服务器的url--" + url);
            MLog.d(TAG,
                    "--POST:提交到 服务器的json数据--" + parser.nameValuePair.toString());
            // 对请求参数进行编码
            post.setEntity(entity);
            HttpResponse response = client.execute(post); // 执行POST方法
            // 返回码的获取，判断处理
            parser.statusCode = response.getStatusLine().getStatusCode();
            if (parser.statusCode == HttpStatus.SC_OK) {
                parser.back = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
            MLog.i(TAG, "返回的数据===" + parser.back);
        } catch (ClientProtocolException e) {
            parser.statusCode = ErrorCode.ERR_CLIENTPROTOCOL;
            MLog.e(TAG, "不符合协议格式", e);
        } catch (ConnectTimeoutException e) {
            parser.statusCode = ErrorCode.ERR_TIMEOUT;
            MLog.e(TAG, "网络连接超时");
        } catch (IllegalStateException e) {
            parser.statusCode = ErrorCode.POOL_SHUT_DOWN;
            MLog.e(TAG, "连接池关闭了", e);
        } catch (SocketException e) {
            if (e.getMessage().contains("ECONNRESET")) {
                parser.statusCode = ErrorCode.ERR_SOCKET;
                MLog.e(TAG, "错误的链接", e);
            } else {
                parser.statusCode = ErrorCode.SHUTDOWN;
                MLog.e(TAG, "端口中断，被中断了", e);
            }
        } catch (Exception e) {
            parser.statusCode = ErrorCode.ERR_UNKNOWN;
            MLog.e(TAG, "网络错误", e);
        } finally {
            save_map.remove(parser);
        }
        return parser;

    }

    /**
     * post 重载方法，方便在外部封装参数部分，而不使用默认封装
     *
     * @param nameValuePair 封装的参数部分
     * @param parser
     * @return
     */
    public static <T extends Parser> T post(
            List<NameValuePair> nameValuePair, T parser) {
        // 此处的map可以不指定
        Context context = parser.context;
        String action = parser.action;

        client = ((MainApplication) context.getApplicationContext())
                .getHttpClient();
        try {
            String url = context.getString(R.string.app_host) + action;
            HttpPost post = new HttpPost(url);

            save_map.put(parser, post); // 将正在处理的对象加入集合
            MLog.d(TAG, "--POST:提交到 服务器的url--" + url);
            MLog.d(TAG, "--POST:提交到 服务器的json数据--" + nameValuePair.toString());
            // 对请求参数进行编码
            post.setEntity(new UrlEncodedFormEntity(nameValuePair, "UTF-8"));

            MLog.i(TAG, "POST编码后的参数是::" + StringUtils.inputStreamToString(post.getEntity().getContent()));
            HttpResponse response = client.execute(post); // 执行POST方法
            // 返回码的获取，判断处理
            parser.statusCode = response.getStatusLine().getStatusCode();
            if (parser.statusCode == HttpStatus.SC_OK) {
                parser.back = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
            MLog.i(TAG, "返回的数据===" + parser.back);
        } catch (ClientProtocolException e) {
            parser.statusCode = ErrorCode.ERR_CLIENTPROTOCOL;
            MLog.e(TAG, "不符合协议格式", e);
        } catch (ConnectTimeoutException e) {
            parser.statusCode = ErrorCode.ERR_TIMEOUT;
            MLog.e(TAG, "网络连接超时");
        } catch (IllegalStateException e) {
            parser.statusCode = ErrorCode.POOL_SHUT_DOWN;
            MLog.e(TAG, "连接池关闭了", e);
        } catch (SocketException e) {
            if (e.getMessage().contains("ECONNRESET")) {
                parser.statusCode = ErrorCode.ERR_SOCKET;
                MLog.e(TAG, "错误的链接", e);
            } else {
                parser.statusCode = ErrorCode.SHUTDOWN;
                MLog.e(TAG, "端口中断，被中断了", e);
            }
        } catch (Exception e) {
            parser.statusCode = ErrorCode.ERR_UNKNOWN;
            MLog.e(TAG, "网络错误", e);
        } finally {
            save_map.remove(parser);
        }
        return parser;

    }

    /**
     * 上传方法,请确认文件是否存在
     * map 中key 为file时 说明value 中含有文件
     * file 的value 为 JSONObject files
     * files 中的 key 为接空中的参数名 value 为文件路径字符串或文件路径array数组
     * value 值 为String 或JSONArray（array对应，传多等情况时）
     *
     * @param parser parser中request值为upload才会执行此方法
     * @return
     */
    public static <T extends Parser> T upload(T parser) {
        long start = System.currentTimeMillis();
        HashMap<String, Object> map = parser.map;
        Context context = parser.context;
        String action = parser.action;
        client = ((MainApplication) context.getApplicationContext())
                .getHttpClient();
        String url = "";
      //  if (context == null) {
           url = parser.url;
        /*} else {
            url = context.getString(R.string.app_host) + action;
        }*/
        try {
            MLog.i(TAG, "--UPLOAD:提交到 服务器的url--" + url);
            HttpPost post = new HttpPost(url);
            save_map.put(parser, post); // 将正在处理的对象加入集合
            MultipartEntityBuilder mEntity = MultipartEntityBuilder.create(); // 从这里开始封装请求信息
            Set<Map.Entry<String, Object>> entrys = map.entrySet();
            Map.Entry<String, Object> entry = null;
            String key = "";
            Object value = "";
            StringBuffer debugStr = new StringBuffer();
            for (Iterator<Map.Entry<String, Object>> it = entrys.iterator(); it.hasNext(); ) {
                entry = it.next();
                key = entry.getKey();
                value = entry.getValue();
                if (key.equalsIgnoreCase("file")) {                // 文件添加
                    JSONObject obj = (JSONObject) value;
                    Iterator<?> files = obj.keys();
                    String next;
                    while (files.hasNext()) {   // 判断是文件标题，进行添加
                        next = files.next().toString();
                        Object content = obj.get(next);
                        if (content instanceof JSONArray) { //用于文件数组
                            JSONArray jcontent = (JSONArray) content;
                            int size = jcontent.length();
                            for (int i = 0; i < size; i++) {
                                String filePath = jcontent.getString(i);
                                File file = new File(filePath);
                                if (!file.exists()) {
                                    MLog.e(TAG, "文件不存在" + filePath);
                                } else {
                                    MLog.d(TAG, "文件path：" + filePath);
                                    //文件存在的话
                                    mEntity.addPart(next, new MyFileBody(file));
                                }
                            }
                        } else {
                            String path = obj.getString(next);
                            MLog.d(TAG, "文件key：" + next + "=====文件path：" + path);
                            // 此处不做文件是否为空判断
                            File file = new File(path);
                            if (!file.exists()) {
                                MLog.e(TAG, "文件不存在" + path);
                            } else {
                                MLog.d(TAG, "文件path：" + path);
                                //文件存在的话
                                mEntity.addPart(next, new FileBody(new File(path)));
                            }
                        }
                    }
                } else { // 文本添加
                    mEntity.addPart(key, new StringBody(value.toString(), ContentType.create("text/plain", Consts.UTF_8)));
                    MLog.i(TAG, "upload文本添加:" + key + "=====" + value);
                    debugStr.append(key + ":" + value.toString() + "\t");
                }
            }

            //如果没有device_token的话,加上
            if (!map.containsKey("device_token")) {
                if (DeviceInfo.UUID == null || DeviceInfo.UUID.equals("")) {
                    SharedPreferences sp = context.getSharedPreferences("config", Context.MODE_PRIVATE);
                    DeviceInfo.UUID = sp.getString("UUID", "");
                }
                mEntity.addPart("device_token", new StringBody(DeviceInfo.UUID, ContentType.create("text/plain", Consts.UTF_8)));
            }

            MLog.i(TAG, "传到服务起的参数是：" + debugStr);
            // 对请求参数进行编码
            post.setEntity(mEntity.build());
            HttpResponse response = client.execute(post); // 执行POST方法
           Header[] h =  response.getAllHeaders();
           for(int i=0;i<h.length;i++){
        	   Log.e("name---",h[i].getName());
        	   Log.e("value---",h[i].getValue());
           }
            
            parser.statusCode = response.getStatusLine().getStatusCode(); // 返回码的获取，判断处理

            if (parser.statusCode == 200) {
                parser.back = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
            MLog.i(TAG, "返回的数据===" + StringUtils.unicodeToUtf8(parser.back));
        } catch (ClientProtocolException e) {
            parser.statusCode = ErrorCode.ERR_CLIENTPROTOCOL;
            MLog.e(TAG, "不符合协议格式", e);
        } catch (ConnectTimeoutException e) {
            parser.statusCode = ErrorCode.ERR_TIMEOUT;
            MLog.e(TAG, "网络连接超时");
        } catch (IllegalStateException e) {
            parser.statusCode = ErrorCode.POOL_SHUT_DOWN;
            MLog.e(TAG, "连接池关闭了", e);
        } catch (SocketException e) {
            if (e.getMessage().contains("ECONNRESET")) {
                parser.statusCode = ErrorCode.ERR_SOCKET;
                MLog.e(TAG, "错误的链接", e);
            } else {
                parser.statusCode = ErrorCode.SHUTDOWN;
                MLog.e(TAG, "端口中断，被中断了", e);
            }
        } catch (Exception e) {
            parser.statusCode = ErrorCode.ERR_UNKNOWN;
            MLog.e(TAG, "网络错误", e);
        } finally {
            save_map.remove(parser);
        }
        MLog.i(TAG, ((System.currentTimeMillis() - start) + ":上传耗时"));
        return parser;
    }

    /**
     * 获得网络连接是否可用
     *
     * @param context
     * @return
     */
    public static boolean hasNetwork(Context context) {
        if (context == null)
            return false;
        ConnectivityManager connect = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connect == null) {
            return false;
        } else {
            NetworkInfo[] info = connect.getAllNetworkInfo();
            if (info != null) {
                for (int i = 0; i < info.length; i++) {
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    /**
     * 封装参数
     *
     * @param map
     * @param nameValuePair
     * @throws org.json.JSONException
     */
    private static void packageParam(HashMap<String, Object> map, List<BasicNameValuePair> nameValuePair, Boolean ifFilter) throws JSONException {
        Set<Map.Entry<String, Object>> entrys = map.entrySet();
        Map.Entry<String, Object> entry;
        String key;
        Object value;
        for (Iterator<Map.Entry<String, Object>> it = entrys.iterator(); it
                .hasNext(); ) {
            entry = it.next();
            key = entry.getKey();
            value = entry.getValue();

            if (ifFilter) {
                if (StringUtils.isNull(key) || value == null || value.equals("")) {
                    continue;
                }
            }
			nameValuePair.add(new BasicNameValuePair(key, value.toString()));
        }
        //如果没有device_token的话,加上
        if (!map.containsKey("device_token")) {
            //nameValuePair.add(new BasicNameValuePair("device_token", DeviceInfo.UUID));
        }
    }

    /**
     * 提供请求中断
     *
     * @param parser 发起请求的parser
     * @return 是否中断成功
     */
    public <T extends Parser> boolean shutdown(T parser) {
        if (parser == null) {
            return false;
        }
        Object obj = save_map.remove(parser);
        if (null == obj) {
            return false;
        } else if (obj instanceof HttpRequestBase) {
            ((HttpRequestBase) obj).abort();
            return true;
        }
        return false;
    }

    public static class MyFileBody extends FileBody {

        public MyFileBody(File file) {
            super(file);
        }

        @Override
        public void writeTo(OutputStream arg0) throws IOException {
            // String name = getFilename().replaceAll("]", "");
            // System.out.println(name + "");
            super.writeTo(new FilterOutputStream(arg0));
        }

    }
}
